<template>
  <div class="model-config-container">
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
        <el-breadcrumb-item>模型配置</el-breadcrumb-item>
      </el-breadcrumb>
      
      <div class="header-title">
        <h1>
          <el-icon class="title-icon"><Setting /></el-icon>
          全局模型配置
        </h1>
        <p class="subtitle">配置和管理AI模型，所有写作功能将使用此处的配置</p>
      </div>
    </div>

    <el-row :gutter="24">
      <!-- 左侧：模型选择和配置 -->
      <el-col :span="14">
        <el-card class="config-card">
          <template #header>
            <div class="card-header">
              <el-icon><Tools /></el-icon>
              <span>模型配置</span>
            </div>
          </template>
          
          <!-- 模型提供商选择 -->
          <div class="provider-section">
            <h3>选择模型提供商</h3>
            <div class="provider-grid">
              <div 
                v-for="(provider, id) in modelStore.providers" 
                :key="id"
                class="provider-card"
                :class="{ active: provider.isActive, configured: provider.hasApiKey }"
                @click="selectProvider(id)"
              >
                <div class="provider-info">
                  <h4>{{ provider.name }}</h4>
                  <p>{{ getProviderDescription(id) }}</p>
                </div>
                <div class="provider-status">
                  <el-icon v-if="provider.hasApiKey" color="#67c23a" size="20">
                    <CircleCheck />
                  </el-icon>
                  <el-icon v-else color="#f56c6c" size="20">
                    <CircleClose />
                  </el-icon>
                  <span v-if="provider.isActive" class="active-badge">使用中</span>
                </div>
              </div>
            </div>
          </div>

          <!-- API密钥配置 -->
          <div class="api-key-section">
            <h3>API密钥配置</h3>
            <el-form :model="apiForm" label-width="120px">
              <el-form-item :label="`${currentProvider?.name} API Key`" v-if="currentProvider">
                <el-input
                  v-model="apiForm.apiKey"
                  type="password"
                  placeholder="请输入API密钥"
                  show-password
                  clearable
                />
              </el-form-item>
              
              <el-form-item label="Base URL" v-if="currentProvider">
                <el-input
                  v-model="apiForm.baseURL"
                  placeholder="可选，自定义API基础地址"
                  clearable
                />
              </el-form-item>
              
              <el-form-item>
                <el-button type="danger" @click="saveApiKey" :loading="testing">
                  保存配置
                </el-button>
                <el-button @click="testConnection" :loading="testing" v-if="currentProvider?.hasApiKey">
                  测试连接
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 模型参数配置 -->
          <div class="model-params-section" v-if="currentProvider?.hasApiKey">
            <h3>模型参数</h3>
            <el-form :model="modelStore.globalConfig" label-width="120px" class="params-form">
              <el-form-item label="模型选择">
                <el-select 
                  v-model="modelStore.globalConfig.model" 
                  placeholder="选择具体模型"
                  style="width: 100%"
                  @change="updateConfig"
                >
                  <el-option 
                    v-for="model in currentProvider.models" 
                    :key="model.id"
                    :label="model.name" 
                    :value="model.id"
                  >
                    <div class="model-option">
                      <span>{{ model.name }}</span>
                      <span class="model-desc">{{ model.description }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="Temperature">
                <el-slider 
                  v-model="modelStore.globalConfig.temperature" 
                  :min="0" 
                  :max="1" 
                  :step="0.1"
                  show-input
                  @change="updateConfig"
                />
                <small class="param-hint">控制输出随机性，0为最确定，1为最随机</small>
              </el-form-item>

              <el-form-item label="Max Tokens">
                <el-input-number 
                  v-model="modelStore.globalConfig.maxTokens" 
                  :min="100" 
                  :max="currentModel?.maxTokens || 8000"
                  :step="100"
                  style="width: 200px"
                  @change="updateConfig"
                />
                <small class="param-hint">最大输出token数量</small>
              </el-form-item>

              <el-form-item label="Top P">
                <el-slider 
                  v-model="modelStore.globalConfig.topP" 
                  :min="0" 
                  :max="1" 
                  :step="0.1"
                  show-input
                  @change="updateConfig"
                />
                <small class="param-hint">核采样参数，控制输出多样性</small>
              </el-form-item>

              <el-form-item label="频率惩罚">
                <el-slider 
                  v-model="modelStore.globalConfig.frequencyPenalty" 
                  :min="0" 
                  :max="2" 
                  :step="0.1"
                  show-input
                  @change="updateConfig"
                />
                <small class="param-hint">降低重复内容的概率</small>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：状态和测试 -->
      <el-col :span="10">
        <el-card class="status-card">
          <template #header>
            <div class="card-header">
              <el-icon><Monitor /></el-icon>
              <span>状态监控</span>
            </div>
          </template>
          
          <!-- 当前配置摘要 -->
          <div class="config-summary">
            <h4>当前配置</h4>
            <div class="summary-item">
              <label>提供商：</label>
              <span>{{ currentProvider?.name || '未选择' }}</span>
            </div>
            <div class="summary-item">
              <label>模型：</label>
              <span>{{ currentModel?.name || '未选择' }}</span>
            </div>
            <div class="summary-item">
              <label>Temperature：</label>
              <span>{{ modelStore.globalConfig.temperature }}</span>
            </div>
            <div class="summary-item">
              <label>Max Tokens：</label>
              <span>{{ modelStore.globalConfig.maxTokens }}</span>
            </div>
          </div>

          <!-- 连接测试 -->
          <div class="test-section" v-if="currentProvider?.hasApiKey">
            <h4>连接测试</h4>
            <div class="test-area">
              <el-input
                v-model="testPrompt"
                type="textarea"
                :rows="4"
                placeholder="输入测试内容..."
                maxlength="200"
                show-word-limit
              />
              <el-button 
                type="danger" 
                @click="runQuickTest" 
                :loading="quickTesting"
                style="width: 100%; margin-top: 12px"
              >
                {{ quickTesting ? '测试中...' : '快速测试' }}
              </el-button>
            </div>
            
            <!-- 测试结果 -->
            <div v-if="testResult" class="test-result">
              <h5>测试结果</h5>
              <div class="result-content">
                <div class="result-meta">
                  <span>用时: {{ testResult.duration }}ms</span>
                  <span>Token: {{ testResult.tokens }}</span>
                  <span v-if="testResult.cost">成本: ${{ testResult.cost.toFixed(6) }}</span>
                </div>
                <div class="result-text" :class="{ error: testResult.error }">{{ testResult.content }}</div>
              </div>
            </div>
          </div>

          <!-- 使用统计 -->
          <div class="usage-stats">
            <h4>使用统计</h4>
            <el-statistic-card title="今日调用">
              <template #value>
                <count-to :start="0" :end="23" />
              </template>
            </el-statistic-card>
            <el-statistic-card title="本月Token">
              <template #value>
                <count-to :start="0" :end="125680" />
              </template>
            </el-statistic-card>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useModelConfigStore } from '@/stores/modelConfig'

const modelStore = useModelConfigStore()

// 响应式数据
const testing = ref(false)
const quickTesting = ref(false)
const testPrompt = ref('请简单介绍一下人工智能的发展历程')
const testResult = ref<any>(null)

// API表单数据
const apiForm = reactive({
  apiKey: '',
  baseURL: ''
})

// 计算属性
const currentProvider = computed(() => {
  return modelStore.getCurrentProvider()
})

const currentModel = computed(() => {
  return modelStore.getCurrentModel()
})

// 方法
const getProviderDescription = (providerId: string) => {
  const descriptions = {
    qwen: '阿里巴巴通义千问大语言模型，支持中英文对话',
    doubao: '字节跳动豆包AI模型，优化了中文理解能力', 
    deepseek: 'DeepSeek推理模型，擅长逻辑推理和代码生成'
  }
  return descriptions[providerId as keyof typeof descriptions] || '优秀的AI语言模型'
}

const selectProvider = (providerId: string) => {
  modelStore.setActiveProvider(providerId)
  
  // 同步表单数据
  const provider = modelStore.providers[providerId]
  apiForm.apiKey = provider.apiKey || ''
  apiForm.baseURL = provider.baseURL || ''
}

const saveApiKey = () => {
  const provider = currentProvider.value
  if (!provider) {
    ElMessage.warning('请先选择一个模型提供商')
    return
  }
  
  if (!apiForm.apiKey.trim()) {
    ElMessage.warning('请输入API密钥')
    return
  }
  
  modelStore.setApiKey(provider.id, apiForm.apiKey.trim())
  
  // 保存Base URL（如果有）
  if (apiForm.baseURL) {
    modelStore.providers[provider.id].baseURL = apiForm.baseURL
  }
  
  ElMessage.success('API密钥保存成功')
}

const testConnection = async () => {
  if (!currentProvider.value) return
  
  testing.value = true
  
  try {
    const result = await modelStore.testConnection(currentProvider.value.id)
    
    if (result.success) {
      ElMessage.success(`连接测试成功，延迟：${result.latency.toFixed(0)}ms`)
    } else {
      ElMessage.error(`连接测试失败：${result.message}`)
    }
  } catch (error) {
    ElMessage.error(`连接测试异常：${error}`)
  } finally {
    testing.value = false
  }
}

const updateConfig = () => {
  // 配置变更时自动保存
  setTimeout(() => {
    modelStore.setGlobalConfig(modelStore.globalConfig)
  }, 100)
}

const runQuickTest = async () => {
  if (!testPrompt.value.trim()) {
    ElMessage.warning('请输入测试内容')
    return
  }
  
  if (!currentProvider.value?.hasApiKey) {
    ElMessage.warning('请先配置API密钥')
    return
  }
  
  quickTesting.value = true
  const startTime = Date.now()
  
  try {
    // 调用真实的AI服务
    const { aiService } = await import('@/services/aiService')
    
    const response = await aiService.generateText({
      userPrompt: testPrompt.value,
      systemPrompt: '你是一个有用的助手，请简洁地回答用户的问题。',
      config: {
        temperature: modelStore.globalConfig.temperature,
        maxTokens: Math.min(modelStore.globalConfig.maxTokens, 500) // 测试时限制token数
      }
    })
    
    testResult.value = {
      duration: response.duration,
      tokens: response.usage.total_tokens,
      content: response.content,
      cost: response.cost
    }
    
    ElMessage.success('测试完成')
  } catch (error) {
    console.error('AI测试错误:', error)
    testResult.value = {
      duration: Date.now() - startTime,
      tokens: 0,
      content: `测试失败：${error instanceof Error ? error.message : String(error)}`,
      error: true
    }
    ElMessage.error(`测试失败：${error instanceof Error ? error.message : String(error)}`)
  } finally {
    quickTesting.value = false
  }
}

// 初始化
onMounted(() => {
  modelStore.initConfig()
  
  // 同步表单数据
  const provider = currentProvider.value
  if (provider) {
    apiForm.apiKey = provider.apiKey || ''
    apiForm.baseURL = provider.baseURL || ''
  }
})
</script>

<style scoped>
.model-config-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.header-title {
  margin-top: 16px;
  text-align: center;
}

.header-title h1 {
  color: #dc3545;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  font-size: 28px;
  font-weight: 600;
}

.title-icon {
  font-size: 32px;
}

.subtitle {
  color: #666;
  margin: 12px 0 0 0;
  font-size: 16px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 16px;
}

.config-card,
.status-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: none;
  border-radius: 12px;
}

/* 提供商选择区域 */
.provider-section {
  margin-bottom: 30px;
}

.provider-section h3 {
  color: #333;
  margin-bottom: 16px;
  font-weight: 600;
}

.provider-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.provider-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 2px solid #e4e7ed;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.provider-card:hover {
  border-color: #dc3545;
  box-shadow: 0 4px 12px rgba(220, 53, 69, 0.15);
}

.provider-card.active {
  border-color: #dc3545;
  background: #fef0f0;
}

.provider-card.configured {
  border-color: #67c23a;
}

.provider-card.configured.active {
  border-color: #dc3545;
  background: #fef0f0;
}

.provider-info h4 {
  margin: 0 0 4px 0;
  color: #333;
  font-weight: 600;
}

.provider-info p {
  margin: 0;
  color: #666;
  font-size: 13px;
}

.provider-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.active-badge {
  background: #dc3545;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

/* API配置区域 */
.api-key-section,
.model-params-section {
  margin-bottom: 30px;
  padding-top: 20px;
  border-top: 1px solid #f0f2f5;
}

.api-key-section h3,
.model-params-section h3 {
  color: #333;
  margin-bottom: 16px;
  font-weight: 600;
}

/* 模型参数表单 */
.params-form .el-form-item {
  margin-bottom: 24px;
}

.model-option {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.model-desc {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.param-hint {
  display: block;
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

/* 右侧状态卡片 */
.status-card {
  height: fit-content;
}

.config-summary {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
}

.config-summary h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-weight: 600;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.summary-item label {
  color: #666;
  font-weight: 500;
}

.summary-item span {
  color: #333;
  font-weight: 600;
}

/* 测试区域 */
.test-section {
  margin: 24px 0;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.test-section h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-weight: 600;
}

.test-area {
  margin-bottom: 16px;
}

.test-result {
  margin-top: 16px;
  padding: 12px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.test-result h5 {
  margin: 0 0 8px 0;
  color: #333;
  font-weight: 600;
  font-size: 14px;
}

.result-content {
  margin-top: 8px;
}

.result-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}

.result-text {
  font-size: 13px;
  line-height: 1.5;
  color: #333;
  padding: 8px;
  background: #fafafa;
  border-radius: 4px;
  border: 1px solid #eee;
}

.result-text.error {
  color: #f56c6c;
  background: #fef0f0;
  border-color: #fbc4c4;
}

/* 统计区域 */
.usage-stats {
  margin-top: 24px;
}

.usage-stats h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .provider-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .model-config-container {
    padding: 15px;
  }
  
  .header-title h1 {
    font-size: 24px;
    flex-direction: column;
    gap: 8px;
  }
  
  .provider-card {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .provider-status {
    align-self: flex-end;
  }
}
</style>